package com.cz.nongyetongv5.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.JingShiXinXiAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.JianChaNeiRong;
import com.cz.nongyetongv5.bean.JingShiXinXi;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

public class JingShiXinXiActivity extends Activity implements OnClickListener {

	private ViewGroup btnBack;

	private ListView listView;

	private JingShiXinXiAdapter adpJingShi;

	/**
	 * 警示信息的数据集合
	 */
	private List<JingShiXinXi> jingShiDatas = new ArrayList<JingShiXinXi>();

	private DatabaseHelper db = null;

	private User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);
		setContentView(R.layout.record_history);

		db = new DatabaseHelper(JingShiXinXiActivity.this,
				CommonConstants.DBNAME, null, CommonConstants.DATABASE_VERSION);

		user = (User) getIntent().getSerializableExtra("user");

		TextView tvTitle = (TextView) findViewById(R.id.tvTitle);

		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);

		listView = (ListView) findViewById(R.id.lvList);

		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

				switch (scrollState) {
					case OnScrollListener.SCROLL_STATE_FLING:

						adpJingShi.setFlagBusy(true);
						break;
					case OnScrollListener.SCROLL_STATE_IDLE:
						adpJingShi.setFlagBusy(false);
						break;
					case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
						adpJingShi.setFlagBusy(false);
						break;
					default:
						break;
				}
				adpJingShi.notifyDataSetChanged();

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
								 int visibleItemCount, int totalItemCount) {

			}
		});

		final String warning = getIntent().getStringExtra("warning");

		final String id = getIntent().getStringExtra("id");

		final int warnInt = Integer.parseInt(warning);

		String title = "警示信息详情";

		switch (warnInt) {
			case 1:
				title = "三品一标警示信息";
				break;

			case 3:
				title = "三品一标警示信息";
				break;

			case 2:

				title = "产地警示信息";

				break;

			case 4:

				title = "产地警示信息";
				break;

			case 5:
				title = "监督检查不合格信息";
				break;

			case 6:

				title = "产品检测不合格信息";

				break;
		}

		tvTitle.setText(title);

		new AsyncTask<Integer, Integer, Integer>() {

			private CustomDialog customDialog = null;

			private int responseCodeRet;
			private String responseBodyRet;

			protected void onPreExecute() {

				customDialog = new CustomDialog(JingShiXinXiActivity.this);

				customDialog.setCanceledOnTouchOutside(true);

				customDialog.setMessage("正在加载..");

				customDialog.showWait();

			};

			@Override
			protected Integer doInBackground(Integer... params) {

				HttpUtils httpUtils = HttpUtils.getInstance();

				String validateUsername = new ConfigUtil(getResources())
						.getRestUsername();

				String validatePassword = new ConfigUtil(getResources())
						.getRestPassword();

				String jingShiXinXiDetailUrl = new ConfigUtil(getResources())
						.getPreHttpUrl()
						+ getString(R.string.jingshixinxi_detail_url)
						+ warning
						+ "/id/" + id;

				httpUtils.setOnRequestExecuted(new OnRequestExecuted() {

					@Override
					public void onRequestExecuted(int responseCode,
												  String responseBody) {

						responseCodeRet = responseCode;
						responseBodyRet = responseBody;
					}
				});

				httpUtils.sendRequest(jingShiXinXiDetailUrl, null, "GET",
						"UTF-8", validateUsername, validatePassword, user);

				return null;
			}

			protected void onPostExecute(Integer result) {

				if (customDialog != null) {
					customDialog.dismiss();
				}

				try {
					// 如果数据获取成功
					if (responseCodeRet == HttpUtils.SUCCESS) {

						try {
							JSONObject jsonObject = new JSONObject(
									responseBodyRet);

							if (!jsonObject.isNull("result")) {

								JSONArray resultJsonArr = jsonObject
										.getJSONArray("result");

								for (int i = 0; i < resultJsonArr.length(); i++) {

									JSONObject itemJsonObj = resultJsonArr
											.getJSONObject(i);

									String name = itemJsonObj.getString("name");

									String serial = itemJsonObj
											.getString("serial");

									String startTime = itemJsonObj
											.getString("expire_begin");

									String endTime = itemJsonObj
											.getString("expire_end");

									String category = "未知";

									int type = itemJsonObj.getInt("category");

									JianChaNeiRong jianChaNeiRong = null;

									if (warnInt == 2 || warnInt == 4) {
										jianChaNeiRong = new JianChaNeiRong(
												null, "无公害产地");

									} else {
										jianChaNeiRong = db
												.queryJianChaNeiRongById(type
														+ "");
									}

									if (jianChaNeiRong != null) {
										category = jianChaNeiRong.getName();
									}

									JingShiXinXi jingShiXinXi = new JingShiXinXi();

									jingShiXinXi.setCategory(category);

									jingShiXinXi.setCategoryInt(warnInt);

									jingShiXinXi.setSerial(serial);

									jingShiXinXi.setName(name);

									jingShiXinXi.setStartTime(startTime);

									jingShiXinXi.setEndTime(endTime);

									jingShiXinXi.setType(type);

									jingShiDatas.add(jingShiXinXi);

								}

								adpJingShi.notifyDataSetChanged();

							}

						} catch (JSONException e) {
							throw new RuntimeException();
						}

					} else {
						throw new RuntimeException();
					}
				} catch (RuntimeException re) {

					DialogUtil.showMessageDialog("加载数据失败..",
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									finish();
								}
							}, JingShiXinXiActivity.this);

				}

			};

		}.execute();

		adpJingShi = new JingShiXinXiAdapter(JingShiXinXiActivity.this,
				jingShiDatas);

		listView.setAdapter(adpJingShi);

		loadRightTitle();

	}

	/**
	 * 加载去主页的按钮
	 */
	public void loadRightTitle() {

		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		View view = GoHomeUtil.createPopView(getApplicationContext(),
				new String[] { "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn0");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					GoHomeUtil.goHome(getApplicationContext());
				}
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

	}

	@Override
	public void onClick(View v) {

		if (v == btnBack) {
			// 返回
			onBackPressed();
		}

	}

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		if (db != null) {
			db.close();
		}

		super.onDestroy();
	}
}
